<route>
    {
        meta: {
            title: "创建用户组"
        }
    }
    </route>

<script setup name="groupExampleAdd">
import useUserGroupStore from '@/store/modules/userGroup'

const route = useRoute()
const router = useRouter()
const topArr = ref([])

const groupStore = useUserGroupStore()

const formRef = ref()

const form = ref({
    name: '',
    parentId: ''
})

const rules = ref({
    name: [
        { required: true, message: '请输入用户组名', trigger: 'blur' }
    ],
    parentId: [
        { required: true, message: '请选择上级用户组', trigger: 'blur' }
    ]

})

onMounted(() => {
    groupStore.getGroup().then(res => {
        handleTop(res)
    })
})

function handleTop(obj) {
    obj.forEach(item => {
        topArr.value.push({ id: item.id, name: item.name })
        if(item.children.length) {
            handleTop(item.children)
        }
    })
}

function onSubmit() {
    formRef.value.validate(valid => {
        if (valid) {
            groupStore.addGroup(form.value).then(() => {
                ElMessage({
                    type: 'success',
                    message: '新增成功'
                })
                router.push({
                    name: 'ComponentExampleGroup'

                })

            }).catch(() => {})
        }
    })
}
</script>

<template>
    <div>
        <page-header title="新增用户组" content="只有管理员账号可以创建用户组~" />
        <page-main>
            <el-row>
                <el-col :md="24" :lg="12">
                    <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
                        <el-form-item label="用户组名" prop="name">
                            <el-input v-model="form.name" placeholder="用户组名" />
                        </el-form-item>

                        <el-form-item label="上级用户组" prop="role">
                            <el-select v-model="form.parentId" placeholder="请选择上级用户组">
                                <el-option v-for="item in topArr" :label="item.name" :value="item.id"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>
                </el-col>
            </el-row>
        </page-main>
        <fixed-action-bar>
            <el-button type="primary" size="large" @click="onSubmit">提交</el-button>
        </fixed-action-bar>
    </div>
</template>
